package com.cykj.page01;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public final class MySever {
    public static void main(String[] args) throws IOException {
        //获取客户端请求的数据
        ServerSocket serverSocket = new ServerSocket(9090);
        System.out.println("服务器启动成功，监听端口：9090");
        Socket socket = serverSocket.accept();
        System.out.println("客户端已连接"+socket.getInetAddress());
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        String request = new String(bytes, 0, len);
        System.out.println("客户端请求的数据"+request);
        //初步解析消息
        String[] lines = request.split("\r\n");//获得每一行
        String firstLine = lines[0];
        String[] parts = firstLine.split(" ");//获得第一行的各个部分
        String imagePath = parts[1];//得到路径部分 abc.png
        //文件读取和文件不存在处理
        byte[] bytes1=null;
        try {
            FileInputStream fis = new FileInputStream("webapps/static/images" + imagePath);
            System.out.println("文件的大小为"+fis.available());
            bytes1 = new byte[fis.available()];
            fis.read(bytes1);
        } catch (FileNotFoundException e) {
            imagePath = "/404.html";
            FileInputStream fis = new FileInputStream("webapps/pages" + imagePath);
            bytes1 = new byte[fis.available()];
            fis.read(bytes1);
        }

        //获取媒体类型
        String media = "";
        String[] splitPath = imagePath.split("\\.");
        if (splitPath[1].equals("html")){
            media="text/html";
        }else if (splitPath[1].equals("jpg")){
            media="image/jpeg";
        }else if (splitPath[1].equals("png")){
            media="image/png";
        }
        //获取输出流
        OutputStream os = socket.getOutputStream();
        os.write("HTTP/1.1 200 OK".getBytes());
        os.write("\r\n".getBytes());
        os.write(("Content-Type:"+media+";charset=UTF-8").getBytes());
        os.write(("Content-Length:"+bytes1.length).getBytes());
        os.write("\r\n".getBytes());
        os.write("\r\n".getBytes());
        os.write(bytes1);
    }
}